package cn.smbms.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.pojo.Provider;
import cn.pojo.User;
import cn.smbms.service.BillService;
import cn.smbms.service.ProviderService;
import cn.smbms.tools.Constants;

@Controller
@RequestMapping("/provider")
public class ProviderController {
	@Autowired
	private ProviderService psi;
	@Autowired
	private BillService bsi;
	
	@RequestMapping("list.html")
	public String listAll(@RequestParam(value="queryProCode",required=false)String code,
			@RequestParam(value="queryProName",required=false)String name,
			Model model){
		model.addAttribute("providerList",psi.getListAll(code, name));
		model.addAttribute("queryProCode",code);
		model.addAttribute("queryProName",name);
		return "providerlist";
	}
	
	@RequestMapping(value="add",method=RequestMethod.GET)
	public String toAdd(@ModelAttribute("provider")Provider pro){
		return "provideradd";
	}
	
	@RequestMapping("save")
	public String saveAdd(Provider pro,HttpSession session){
		pro.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId()+"");
		pro.setCreationDate(new Date());
		if(psi.addProvider(pro)>0){
			return "redirect:list.html";
		}
		return "provideradd";
	}
	
	@RequestMapping(value="add",method=RequestMethod.POST)
	public String toAdd_save(@Valid Provider pro,BindingResult bin, HttpSession session,
			HttpServletRequest request,
			@RequestParam(value = "PicPath", required = false) MultipartFile[]PicPath){
		
		if(bin.hasErrors()){
			return "provideradd";
		}
		
		String licPicPath=null;
		String codePicPath=null;
		for (int i = 0; i < PicPath.length; i++) {
			if(i==0){
				licPicPath=upLoad(PicPath[i],request);
			}
			if(i==1){
				codePicPath=upLoad(PicPath[i],request);
			}
		}
		pro.setCodePicPath(codePicPath);
		pro.setLicPicPath(licPicPath);
		pro.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId()+"");
		pro.setCreationDate(new Date());
		if(psi.addProvider(pro)>0){
			return "redirect:list.html";
		}
		return "provideradd";
	}
	
	@RequestMapping(value="view/{id}",method=RequestMethod.GET)
	public String view(@PathVariable String id,Model model){
		Provider pro=psi.getById(id);
		model.addAttribute("provider",pro);
		return "providerview";
	}
	
	@RequestMapping(value="modify",method=RequestMethod.GET)
	public String modify(String id,Model model){
		Provider pro=psi.getById(id);
		model.addAttribute("provider",pro);
		return "providermodify";
	}
	
	@RequestMapping(value="modifySave.html",method=RequestMethod.POST)
	public String modifySave(Provider pro,HttpSession session,HttpServletRequest request,
			@RequestParam(value = "PicPath", required = false) MultipartFile[]PicPath){
		pro.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		pro.setModifyDate(new Date());
		String licPicPath=null;
		String codePicPath=null;
		for (int i = 0; i < PicPath.length; i++) {
			if(i==0){
				licPicPath=upLoad(PicPath[i],request);
			}
			if(i==1){
				codePicPath=upLoad(PicPath[i],request);
			}
		}
		pro.setCodePicPath(codePicPath);
		pro.setLicPicPath(licPicPath);
		
		
		if(psi.providerUp(pro)>0){
			return "redirect:/provider/list.html";
		}
		return "providermodify";
	}
	
	@RequestMapping("del")
	@ResponseBody
	public Object delProvider(String proid){
		HashMap<String, String> resultMap=new HashMap<String,String>();
		int num=psi.delProvider(proid);
		if(num>0){
			resultMap.put("delResult", "true");
		}else if(num==0){
			resultMap.put("delResult", "notexist");
		}else if(num==-1){
			resultMap.put("delResult", bsi.BillByProId(proid)+"");
		}else{
			resultMap.put("delResult", "false");
		}
		return resultMap;
	}
	
	public String upLoad(MultipartFile attach,HttpServletRequest request){
		String PicPath=null;
		if (!attach.isEmpty()) {
			//获取路径
			String path = request.getSession().getServletContext().getRealPath
					("statics" + File.separator + "uploadFile");
			//设置文件名
			String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
			//控制大小
			if(attach.getSize()>500000){
				request.setAttribute("uploadFileError", "文件大小不能超过500KB");
				System.out.println("文件大小错误！");
				return null;
			}
			
			File targetFile=new File(path,fileName);
			if(!targetFile.exists()){
				targetFile.mkdirs();
			}
			try{
				attach.transferTo(targetFile);
				PicPath=request.getContextPath() + File.separator + "statics" + 
						 File.separator + "uploadFile" + File.separator + fileName;
			}catch(Exception e){
				e.printStackTrace();
				System.out.println("错误！");
				return null;
			}
		}
		return PicPath;
	}
	
}
